// pages/store/category.js
const app = getApp()
const background = ['#E09132', '#A9AE36', '#DAAB1D', '#5CAA5F'];
let index = 0;
let timeid = 0;
Page({
    /**
     * 页面的初始数据
     */
    data: {
        tbg: background[Math.floor(Math.random() * background.length)],
        // is_keep: false,
        status: "list",
        loading: true,
        show: false,
        mask: false,
        index: 0,
        current: 0,
        current2: 0,
        count: 0,
        cart: {},
        isActivity:false,
        activity:[
            { title:'折扣商品6.19折起'},
            { title:'新品全场8.9折'},
        ]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData(options);
        clearInterval(timeid)
        timeid = setInterval(() => {
            index++;
            if (index > background.length - 1) {
                index = 0;
            }
            this.setData({
                tbg: background[index],
            })
        }, 5000)
    },
    loadCategory() {
        wx.showLoading({
            title: '加载中...',
        })
        app.http.get("supplier/index", {
            data: {
                id: this.data.id,
                saleMemberId: this.data.sellMemberId ? this.data.sellMemberId : ''                
            }
        }).then(res => {
            console.log(res)
            this.setData({
                loading: false
            })
            this.setData(res.data)
            let cid = 0;
            for (let i = 0; i < res.data.category.length; i++) {
                if (res.data.category[i].categories.length) {
                    res.data.category[i].isOpen = true
                    cid = res.data.category[i].categories[0].category_id
                    break;
                }
            }
            res.data.category[0].isOpen = true;
            this.setData({
                // category: [{ category_id: 0, name: "全部" }].concat(res.data.category),
                category: res.data.category,
                store: res.data.store,
                goods: res.data.item,
                isApply: res.data.isApply,
                cid,
            });
            wx.stopPullDownRefresh()
            wx.setNavigationBarTitle({
                title: this.data.store.supplier_name,
            })
            wx.hideLoading()
        }).catch(err => {
            app.wxToast.error(err.message) 
            setTimeout(function(){
                wx.navigateBack()
            },3000)
        })
    },

    loadGoods() {
        let { current, current2, page = 2, total = 3, goods = [], loading = false } = this.data
        if (page > total || loading) {
            return
        }
        this.setData({
            loading: true
        })
        const data = {
            id: this.data.id,
            saleMemberId: this.data.sellMemberId ? this.data.sellMemberId : null,
            page
        }
        if (current != undefined) {
            data["SupplierGoodsSearch[category_id_f]"] = this.data.category[current].category_id
            if (current2 != undefined) {
                data["SupplierGoodsSearch[category_id_s]"] = this.data.category[current].categories[current2].category_id
            }
        }

        app.http.get("supplier/index", {
            data,
        }).then(res => {
            page++
            total = res.data.total
            goods.push(...res.data.item)
            this.setData({
                loading: false,
                page, total,
                goods
            });
        })
    },
    lower() {
        this.loadGoods()
    },
    setStatus: function (evt) {
        this.setData({
            status: evt.currentTarget.dataset.status
        })
    },
    //菜品分类点击
    menuClick: function (evt) {
        let { category, current, current2, cid } = this.data
        const { index, id, cindex } = evt.currentTarget.dataset

        if (cindex === undefined) {
            if (index == current) {
                this.setData({
                    [`category[${index}].isOpen`]: !category[index].isOpen
                })
            } else {
                category.forEach(o => {
                    o.isOpen = category[index].category_id == o.category_id
                })
                current = index
                this.setData({
                    category,
                    current
                })
            }
        } else {
            if (cid != id) {
                current2 = cindex
                this.setData({
                    cid: category[index].categories[cindex].category_id,
                    current2,
                    page: 1,
                    total: 2,
                    goods: []
                })
                this.loadGoods()
            }
        }
    },

    /**
    * 收藏
    **/
    collection() {
        app.http.get("member/keep", {
            data: {
                id: this.data.id
            }
        }).then(res => {
            this.setData({
                isKeep: !this.data.isKeep,
            })
        }).catch(err => {
            app.wxToast.error(err.message)
        })
    },

    setNum(evt) {
        let cart = this.data.cart
        const { item, step = 1 } = evt.currentTarget.dataset
        const key = "goods" + item.goods_id
        if (!cart[key]) {
            cart[key] = { num: 0 }
        }

        var f = function () {
            this.setData({
                [`cart.${key}.name`]: item.good.goods_name,
                [`cart.${key}.price`]: +item.price_num,
                [`cart.${key}.num`]: cart[key].num += +step
            })
            this.update()
        }

        if (step == 1) {
            wx.showLoading({
                title: '加载中...',
            })
            app.http.get('supplier/attr', {
                data: {
                    id: item.goods_id,
                    sid: this.data.id
                }
            }).then(res => {
                wx.hideLoading()
                if (res.data.spec.length > 0) {
                    this.setData({
                        selectedGoods: item,
                        spec: res.data.spec,
                        sku: res.data.sku,
                        model: 1
                    })
                } else {
                    f.call(this)
                }
            })
        } else {
            this.cartClick()
        }

    },

    clickSpec(evt) {
        const [x, y] = evt.currentTarget.dataset.pos

        this.setData({
            [`spec[${x}].selected`]: y
        })
        let skuName = this.data.spec.map(o => {
            return o.child[o.selected] ? o.child[o.selected].name : "--"
        }).join("#")
        this.setData({
            selectedSku: this.data.sku.find(o => o.name == skuName),
        })
        this.update()
    },

    submitSpec(evt) {
        let cart = this.data.cart
        const { selectedGoods, selectedSku } = this.data
        const key = "goods" + selectedGoods.goods_id + "#" + selectedSku.id
        if (!cart[key]) {
            cart[key] = { num: 0 }
        }
        this.setData({
            [`cart.${key}.name`]: selectedGoods.good.goods_name + "(" + selectedSku.name + ")",
            [`cart.${key}.price`]: +selectedGoods.price_num + (+selectedSku.price),
            [`cart.${key}.num`]: cart[key].num + 1,
            [`cart.${key}.sku`]: selectedSku,
            model: 0,
            selectedGoods: null,
            selectedSku: null
        })
        this.update()
    },

    update() {
        let totalNum = 0, totalPrice = 0, cartData = []
        Object.keys(this.data.cart).forEach(o => {
            const { num, price, name } = this.data.cart[o]
            if (num == 0) {
                return
            }
            totalNum += num
            totalPrice += num * price
            // console.log(price, 'xxx')
            cartData.push({
                id: o.replace("goods", ""),
                price: price,
                num,
                name
            })
        })
        
        this.setData({
            totalNum,
            totalPrice,
            cartData
        })
    },


    phoneClick: function () {
        wx.makePhoneCall({
            phoneNumber: this.data.store.tell,
        })
    },

    cartClick() {
        this.setData({
            showCart: 1,
        })
    },
    closeCart() {
        this.setData({
            showCart: 0,
            model: 0
        })
    },
    modelClick() {
        this.setData({
            model: 1,
        })
    },
    cartNumClick(evt) {
        const { id, step } = evt.currentTarget.dataset
        const key = "goods" + id
        this.setData({
            [`cart.${key}.num`]: this.data.cart[key].num += +step
        })
       
        this.update()
        if (this.data.cartData.length == 0) {
            this.closeCart()
        }
    },

    addrClick: function () {
        wx.openLocation({
            latitude: parseFloat(this.data.store.lat),
            longitude: parseFloat(this.data.store.lng),
            scale: 28,
            name: this.data.store.supplier_name,
            address: this.data.store.address
        })
    },
    submit() {
        if (this.data.totalNum <= 0) {
            return;
        }
        if (this.data.sellMemberId){
            wx.navigateTo({
                url: 'pay?sid=' + this.data.id + '&sell_member_id=' + this.data.sellMemberId,
            })
        }else{
            wx.navigateTo({
                url: 'pay?sid=' + this.data.id
            })
        }
        // wx.navigateTo({
        //     url: 'pay?sid=' + this.data.id + '&sell_member_id=' + this.data.sellMemberId,
        // })
    },
    apply() {
        wx.showToast({
            title: '先申请认证，查看价格哦~',
        })
    },

    /**
     * 活动
     */
    checkActivity(){
        this.setData({
            isActivity: !this.data.isActivity
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.loadCategory();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.loadCategory()
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: "这家店不错，来逛逛吧~",
            path: '/pages/order-system/other-store/store-detail?sid=' + app.storeId + '&type=' + this.data.type
        }
    },

})